home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17843 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  48 lines

  1. Newsgroups: comp.lang.c++
  2. Path: link-1.ts.bcc.ac.uk!ucecb09
  3. From: ucecb09@ucl.ac.uk (Robert Byrne)
  4. Subject: Re: Friend vs. Member function for operator overload
  5. Message-ID: <1996Apr15.104234.55653@ucl.ac.uk>
  6. Date: Mon, 15 Apr 1996 10:42:34 GMT
  7. References: <4kj55n$mv2@homenet.hom.net> <316E6F5E.2F1C@lmf-di.puc-rio.br>
  8. Organization: University College London
  9.  
  10. Paulo Eduardo Neves <neves@lmf-di.puc-rio.br> writes:
  11.  
  12. >Daniel P. Engel III wrote:
  13. >> 
  14. >> Can anyone tell me if one of these the "preferred" way of doing it?
  15. >> And, what are the advantages and disadvantages of each?
  16. >> 
  17.  
  18. >When you use a friend function your code becomes more consistent, since
  19. >the same conversions  can be applied to both arguments. See a operator+
  20. >defined as friend in a string class that has a ctor from a standard c
  21. >string :
  22.  
  23. However, there's usually no need to make arithmetic operators friends
  24. as they can simply call the appropriate assignment op. To whit;
  25.  
  26.   struct String
  27.   {
  28.     String &operator+=(const String &);
  29.     String(const String&);
  30.     String(const char*);
  31.     //...
  32.   };
  33.  
  34.   String operator+(const String & lhs, const String &rhs)
  35.   {
  36.     return String(lhs) += rhs;
  37.   }
  38.  
  39. Giving the advantage of symmetry for the args but w/o adding friends
  40. and keeping all the code within the class.
  41.  
  42. Rob
  43.  
  44. --
  45. Robert Byrne         `I think therefore I am' says rather more than
  46. ucecb09@ucl.ac.uk     is strictly certain.'       -Bertrand Russell
  47.  
  48.